<template>
	<view class="page-wrap">
		<view>
			<view class="topbar">
				<image class="logo" src="/static/logo.png"></image>
			</view>
			<view class="toolbar">
				<view class="toolbar-wrap" v-if="mode == EMode.Shopping">
					<view class="mode-wrap" @click="switchMode(EMode.Manager)">
						<uni-icons class="toolbar-icon" type="shop-filled" size="32" color="#f1d145"></uni-icons>
						<label>营业模式</label>
					</view>
				</view>
				<view class="toolbar-wrap" v-if="mode == EMode.Manager">
					<view class="mode-wrap" @click="switchMode(EMode.Shopping)">
						<uni-icons class="toolbar-icon" type="gear-filled" size="32" color="#f1d145"></uni-icons>
						<label>管理模式</label>
					</view>
					<view class="toolbar-right">
						<uni-icons class="toolbar-right-icon" type="plusempty" size="24" color="#f1d145" @click="onClickAdd"></uni-icons>
					</view>
				</view>
			</view>
		</view>
		<view class="tagbar">
			<view :class="{ 'tag': true, 'tag-selected': selectedTag == tag }" v-for="(tag, index) in allTags" :key="index" @click="onSelectTag(tag)">
				<text>{{ tag }}</text>
			</view>
		</view>
		<uni-list class="main-wrap" :border="true">
			<uni-list-item v-for="(item, index) in displayGoods" :key="index">
				<template v-slot:body>
					<view :class="{'list-item-body': true, 'list-item-gray': item.price == 0}">
						<view class="list-item-detail">
							<view class="name-wrapper">
								<view class="tag-color" :style="'background-color: ' + getTagColor(item.name) + '; color: ' + getTagColor(item.name)">·</view>
								<view>{{ item.name }}</view>
							</view>
							<text v-if="mode == EMode.Shopping">{{ `￥${item.price}` }}</text>
						</view>
						<view class="list-item-right" v-if="mode == EMode.Shopping">
							<text class="list-item-price" v-if="buyCntMap[item.name] > 0">{{ `￥${item.price * buyCntMap[item.name]}` }}</text>
							<uni-number-box v-if="buyCntMap[item.name] > 0" v-model="buyCntMap[item.name]" background="#f1d145" color="#fff" />
							<uni-icons v-if="buyCntMap[item.name] == 0" type="plus" size="28" color="#f1d145" @click="onClickBuy(item)"></uni-icons>
						</view>
						<view class="list-item-right" v-if="mode == EMode.Manager">
							<text class="list-item-price">{{ `￥${item.price}` }}</text>
							<uni-icons type="gear-filled" size="28" color="#f1d145" @click="onClickEdit(item)"></uni-icons>
						</view>
					</view>
				</template>
			</uni-list-item>
		</uni-list>
		<view class="footbar">
			<uni-icons type="scan" size="44" @click="startScan"></uni-icons>
			<view class="bill">
				<uni-icons type="cart-filled" size="44" @click="onPreview"></uni-icons>
				<text>{{ `￥${totalAmount}` }}</text>
			</view>
		</view>
	</view>
	<view>
		<uni-popup ref="popup" background-color="#fff">
			<view v-if="isPreview">
				<view class="bill-content">
					<view class="bill-content-item">
						<text class="bill-content-item-name">商品</text>
						<text class="bill-content-item-other">数量</text>
						<text class="bill-content-item-other">单价</text>
						<text class="bill-content-item-other">金额</text>							
					</view>
					<view class="bill-content-item" v-for="(b, bindex) in previewBill.buys" :key="bindex">
						<text class="bill-content-item-name">{{ b.name }}</text>
						<text class="bill-content-item-other">{{ b.cnt }}</text>
						<text class="bill-content-item-other">{{ '￥' + b.price }}</text>
						<text class="bill-content-item-other">{{ '￥' + b.price * b.cnt }}</text>
					</view>
					<view class="bill-content-item">
						<text class="bill-content-item-name">总计</text>
						<text class="bill-content-item-other">{{ totalCnt }}</text>
						<text class="bill-content-item-other"></text>
						<text class="bill-content-item-other">{{  '￥' + totalAmount }}</text>							
					</view>
					<view class="popup-editor-btnrow">
						<button class="popup-editor-button" @click="resetBuy">清空</button>
						<button class="popup-editor-button" @click="recordBuy">记一笔</button>
					</view>
				</view>
			</view>
			<view v-if="!isPreview && selectedGood" class="popup-content">
				<view class="popup-detail">
					<text class="text">{{ selectedGood.name }}</text>
				</view>
				<view  class="scan-result" v-if="mode == EMode.Shopping">
					<view class="popup-editor-row">
						<text class="scan-row-left">单价：</text>
						<text class="scan-row-right">{{ '￥' + selectedGood.price }}</text>
					</view>
					<view class="popup-editor-row">
						<text class="scan-row-left">数量：</text>
						<uni-number-box v-model="buyCntMap[selectedGood.name]" background="#f1d145" color="#fff" @change="onNumChange"/>
					</view>
					<view class="popup-editor-row">
						<text class="scan-row-left">总价：</text>
						<text class="scan-row-center">{{ '￥' + (selectedGood.price * (buyCntMap[selectedGood.name] || 0))}}</text>
					</view>
					<button class="popup-editor-button" @click="onClickScanContinue">继续扫</button>
				</view>
				<view v-if="mode == EMode.Manager">
					<form class="editor-form" @submit="onClickEditSubmit">
						<view class="popup-editor-row">
							<text class="editor-row-label editor-row-left">标签：</text>
							<view class="tag-wrap">
								<view class="tag" v-for="(tag, index) in (selectedGood.tags || [])" :key="index">{{ tag }}
									<uni-icons class="tag-x" type="closeempty" size="12" color="#f1d145" @click="onClickEditDelTag(tag)"></uni-icons>
								</view>
								<uni-icons type="plusempty" size="20" color="#f1d145" @click="onClickEditAddTag"></uni-icons>
							</view>
						</view>
						<view class="popup-editor-row">
							<text class="editor-row-label editor-row-left">条码：</text>
							<text class="editor-row-label editor-row-center">{{ tmpCode || selectedGood.code || '无' }}</text>
							<uni-icons class="editor-row-right" type="scan" size="20" color="#f1d145" @click="onClickEditScan"></uni-icons>
						</view>
						<view class="popup-editor-row">
							<text class="editor-row-label editor-row-left">单价：</text>
							<input class="popup-editor-input editor-row-center" name="price" type="number" inputmode="decimal" confirm-type="完成" focus placeholder="请输入价格" :value="String(selectedGood.price)" />
						</view>
						<view class="popup-editor-btnrow">
							<button class="popup-editor-button" @click="onClickEditDel">删除</button>
							<button form-type="submit" class="popup-editor-button">确定修改</button>
						</view>
					</form>
				</view>	
			</view>
		</uni-popup>
	</view>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { ref } from 'vue';
import { convertToPynum } from '../../engine/py.js';
import moment from 'moment';
import { __tags } from '../../engine/goods.js';

enum EMode {
	Shopping,
	Manager
}

const isPreview = ref(false);
const goodColorMap: Record<string, string> = {};
for (const g of engine.dataMgr.goods.value) {
	if (goodColorMap[g.name]) console.error('repeat good: ' + g.name);
	if (!g.tags) goodColorMap[g.name] = '#FFF';
	else goodColorMap[g.name] = engine.getTagColor(g.tags[0]);
}
const selectedGood = ref<engine.GoodInfo>();
const mode = ref<EMode>(EMode.Shopping);
const buyCntMap = ref<{ [name: string]: number }>({});
const totalCnt = computed(() => {
	let tc = 0;
	for (const g of engine.dataMgr.goods.value) {
		const cnt = buyCntMap.value[g.name];
		if (cnt > 0) {
			tc += cnt;
		}
	}
	return tc;
});
const totalAmount = computed(() => {
	let ta = 0;
	for (const g of engine.dataMgr.goods.value) {
		const cnt = buyCntMap.value[g.name];
		if (cnt > 0) {
			ta += cnt * g.price;
		}
	}
	return ta;
});
const previewBill = computed(() => {
	const buys: engine.BuyInfo[] = [];
	let totalAmount = 0;
	for (const g of engine.dataMgr.goods.value) {
		const cnt = buyCntMap.value[g.name];
		if (cnt > 0) {
			buys.push({ name: g.name, cnt, price: g.price });
			totalAmount += g.price * cnt;
		}
	}
	const bill: engine.BillInfo = { time: moment.now(), buys, totalAmount };
	return bill;
});
const allTags = computed(() => {
	const tags: string[] = [];
	for (const g of engine.dataMgr.goods.value) {
		if (!g.tags) continue;
		for (const tag of g.tags) {
			if (!tags.includes(tag)) {
				tags.push(tag);
			}
		}
	}
	tags.sort((a, b) => convertToPynum(a) - convertToPynum(b));
	return tags;
});
const selectedTag = ref<string>('');
const displayGoods = computed(() => {
	let arr: engine.GoodInfo[];
	if (!selectedTag.value) {
		arr = engine.dataMgr.goods.value;
	} else {
		arr = engine.dataMgr.goods.value.filter((v) => v.tags?.includes(selectedTag.value));
	}
	return arr.sort((a, b) => {
		const labelA = a.tags?.[0], labelB = b.tags?.[0];
		if (labelA == labelB) {
			return convertToPynum(a.name) - convertToPynum(b.name);
		}
		if (labelA && !labelB) return -1;
		if (!labelA && labelB) return 1;
		const tidxA = __tags.indexOf(labelA!), tidxB = __tags.indexOf(labelB!);
		if (tidxA >= 0 && tidxB >= 0) return tidxA - tidxB;
		if (tidxA >= 0 && tidxB < 0) return -1;
		if (tidxA < 0 && tidxB >= 0) return 1;
		return convertToPynum(labelA!) - convertToPynum(labelB!);
	})
});
const getTagColor = (goodName: string) => {
	return goodColorMap[goodName];
}

const tmpCode = ref<string>('');
const popup = ref<ui.Popup>();

const onSelectTag = (tag: string) => {
	if (selectedTag.value == tag) {
		selectedTag.value = '';
	} else {
		selectedTag.value = tag;
	}
}

const switchMode = (m: EMode) => {
	mode.value = m;
	if (m == EMode.Shopping) {
		resetBuy();
	}
}

const startScan = () => {
	uni.scanCode({
		scanType: ['barCode'],
		success(result) {
			for (const g of engine.dataMgr.goods.value) {
				if (g.code == result.result) {
					selectedGood.value = g;
					isPreview.value = false;
					popup.value?.open('bottom');
					return;
				}
			}
			uni.showToast({
				title: '商品识别失败！',
				icon: 'error'
			});
		}
	});
}

const onNumChange = (value: number) => {
	buyCntMap.value[selectedGood.value!.name] = value;
}

const onClickScanContinue = () => {
	popup.value?.close();
	startScan();
}

const onPreview = () => {
	isPreview.value = true;
	popup.value?.open('bottom');
}

const recordBuy = () => {
	// 记一笔
	const bill = previewBill.value;
	engine.dataMgr.addBills([bill]);
	resetBuy();
}

const resetBuy = () => {
	const map: { [name: string]: number } = {};
	for (const g of engine.dataMgr.goods.value) {
		map[g.name] = 0;
	}
	buyCntMap.value = map;
	popup.value?.close();
}

const onClickBuy = (item: engine.GoodInfo) => {
	buyCntMap.value[item.name] = 1;
}

const onClickAdd = () => {
	uni.showModal({
		title: '添加商品',
		editable: true,
		placeholderText: '请输入商品名称',
		success(result) {
			if (result.confirm && result.content) {
				for (const g of engine.dataMgr.goods.value) {
					if (g.name == result.content) {
						uni.showToast({
							title: '已存在相同商品！',
							icon: 'error'
						});
						return;
					}
				}
				engine.dataMgr.goods.value.push({ name: result.content, price: 0 });
				engine.dataMgr.saveGoods();
			}
		}
	});	
}

const onClickEdit = (item: engine.GoodInfo) => {
	tmpCode.value = '';
	selectedGood.value = item;
	isPreview.value = false;
	popup.value?.open('bottom');
}

const onClickEditDelTag = (tag: string) => {
	if (selectedGood.value && selectedGood.value.tags) {
		const idx = selectedGood.value.tags.indexOf(tag);
		if (idx >= 0) {
			selectedGood.value.tags.splice(idx, 1);
		}
	};
}

const onClickEditAddTag = () => {
	uni.showModal({
		title: '添加标签',
		editable: true,
		showCancel: true,
		placeholderText: '请输入标签名',
		success(result) {
			if (result.confirm && result.content) {
				if (selectedGood.value) {
					if (!selectedGood.value.tags) {
						selectedGood.value.tags = [result.content];
					} else if (!selectedGood.value.tags.includes(result.content)) {
						selectedGood.value.tags.push(result.content);
					}
				}
			}
		}
	});
}

const onClickEditScan = () => {
	uni.scanCode({
		scanType: ['barCode'],
		success(result) {
			console.log('scan result:', result);
			if (selectedGood.value) {
				tmpCode.value = result.result;
				engine.dataMgr.saveGoods();
			}
		}
	})
}

const onClickEditDel = () => {
	console.log('on click del!');
	if (selectedGood.value) {
		const idx = engine.dataMgr.goods.value.findIndex((v) => v.name == selectedGood.value?.name);
		if (idx >= 0) {
			engine.dataMgr.goods.value.splice(idx, 1);
			engine.dataMgr.saveGoods();
		}
		selectedGood.value = undefined;
		popup.value?.close();
		// console.log('price', priceInput.value.value);
	}
}

const onClickEditSubmit = (payload: Event) => {
	console.log('on click submit!', payload);
	if (selectedGood.value) {
		const price = Number((payload as ui.FormEvent).detail.value.price);
		if (isNaN(price)) {
			uni.showToast({
				title: '价格错误，请重新输入',
				icon: 'error'
			});
			return;
		}
		if (!isNaN(price)) {
			selectedGood.value.price = price;
		}
		if (tmpCode.value) {
			selectedGood.value.code = tmpCode.value;
		}
		engine.dataMgr.saveGoods();
	}
	popup.value?.close();
}

resetBuy();
</script>

<style lang="scss">
$tagbar-height: 32px;

.main-wrap {
	height: calc(100vh - $topbar-height - $toolbar-height - $tagbar-height - $footbar-height - 10px);
	overflow-y: scroll;
}

.toolbar {
	@include flex;
	height: $toolbar-height;
	padding-left: 20px;
	padding-right: 20px;
	padding-top: 6px;
}

.toolbar-icon {
	line-height: 100%;
}

.toolbar-wrap {
	@include flex;
	width: 100%;
	justify-content: space-between
}

.toolbar-right {
	@include flex;
	justify-content: right;
}

.toolbar-right-icon {
	@extend .toolbar-icon;
	margin-left: 20px;
}

.mode-wrap {
	@include flex;
	height: 100%;
	line-height: 100%;
}

.list-item-body {
	@include flex;
	width: 100%;
	height: 24px;
	line-height: 100%;
	justify-content: space-between;
	font-size: 18px;
}

.list-item-gray {
	color: #888888;
	filter: grayscale(100%);
}

.list-item-detail {
	@include flex;
	justify-content: space-between;
	line-height: 100%;
	width: 50%;
}

.list-item-right {
	@include flex;
	flex: 1;
	justify-content: right;
}

.list-item-price {
	margin-right: 10px;
}

.tagbar {
	@include flex;
	justify-content: left;
	min-width: 100%;
	height: $tagbar-height;
	padding-left: 10px;
	overflow-x: scroll;
}

.popup-content {
	@include flex-v;
	align-items: center;
	justify-content: center;
	padding: 32px;
	// height: 250px;
	background-color: #fff;
	font-size: 20px;
}

.popup-detail {
	@include flex;
	height: 50px;
}

.scan-result {
	@include flex-v;
	justify-content: space-between;
	width: 100%;
}

.scan-result-row {
	@include flex;
	width: 100%;
	height: 40px;
	justify-content: center;
}

.scan-row-left {
	width: 80px;
	height: 40px;
	line-height: 40px;
}

.scan-row-right {
	width: 200px;
	height: 40px;
	line-height: 40px;
}

.editor-form {
	@include flex-v;
	justify-content: space-between;
	width: 100%;
	height: 200px;
}

.popup-editor-row {
	@include flex;
	width: 100%;
	height: 40px;
	justify-content: left;
}

.popup-editor-btnrow {
	@include flex;
	width: 100%;
	height: 40px;
	justify-content: space-between;
}

.editor-row-left {
	width: 20%;
}

.editor-row-center {
	width: 60%;
}

.editor-row-right {
	width: 20%;
}

.popup-editor-input {
	height: 24px;
	line-height: 24px;
	border-bottom: 1 dotted $theme-color;
}

.popup-editor-button {
	@include theme-bg;
	width: 100px;
	height: 36px;
	line-height: 36px;
	font-size: 14px;
	color: #fff;
}

.editor-row-label {
	height: 24px;
	line-height: 24px;
}

.tag-wrap {
	@include flex;
	align-items: center;
	height: 24px;
	line-height: 24px;
}

.tag {
	@include theme-color;
	height: 20px;
	line-height: 20px;
	margin-right: 8px;
	font-size: 12px;
	border: 1px solid $theme-color;
	padding: 2px;
	border-radius: 2px;
}

.tag-selected {
	@include theme-bg;
	color: #fff;
}

.tag-x {
	position: relative;
	top: 0;
	right: 0;
}

.bill-content {
	@include flex-v;
	padding: 10px 20px 10px 20px;
}

.bill-content-item {
	@include flex;
	height: 32px;
	line-height: 32px
}

.bill-content-header {
	@extend .bill-content-item;
	border-bottom: 10x dotted gray;
}

.bill-content-item-name {
	flex: 55%;
}

.bill-content-item-other {
	flex: 15%;
}
.name-wrapper {
	@include flex;
}
.tag-color {
	min-width: 8px;
	height: 100%;
}

</style>
